package kevin.framework.basic.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import kevin.framework.basic.common.ui.AjaxResult;
import kevin.framework.basic.common.user.LoginUser;
import kevin.framework.basic.common.utils.DESBase64Util;
import kevin.framework.basic.common.utils.MyUUID;
import kevin.framework.basic.common.utils.SysConfigParams;
import kevin.framework.basic.domain.Menu;
import kevin.framework.basic.domain.User;
import kevin.framework.basic.service.IBaseService;
import kevin.framework.basic.service.IFuncService;
import kevin.framework.basic.service.IMenuService;
import kevin.framework.basic.service.IUserRoleService;
import kevin.framework.basic.service.IUserService;

@Controller
@RequestMapping(value = "/main")
public class DefaultController extends ResetfulBaseController<User, String> {

    IUserService userService;

    @Resource(name = "userService")
    @Override
    public void setService(IBaseService<User, String> service) {
        this.service = service;
        userService = (IUserService)service;
    }

    @Resource(name = "funcService")
    IFuncService funcService = null;

    @Resource(name = "userRoleService")
    IUserRoleService userRoleServie;

    @Resource(name = "menuService")
    IMenuService menuService;

    private static Font mFont = new Font("Times New Roman", Font.PLAIN, 24);
    static int width = 80, height = 30;

    Color getRandColor(int fc, int bc) {
        Random random = new Random();
        if (fc > 255) {
            fc = 255;
        }
        if (bc > 255) {
            bc = 255;
        }
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }

    @Override
    @RequestMapping(value = "/page/{pageName}", method = RequestMethod.GET)
    public String page(@PathVariable("pageName") String pageName, HttpServletRequest request) throws Exception {
        if ("login".equals(pageName)) {
            LoginUser user = this.getLoginUser();
            if (user != null) {
                pageName = "index";// 如果已经登录
            }
        }
        String cfgString = "config.js";
        if ("index3".equals(pageName) || "index".equals(pageName) || "index2".equals(pageName)) {
            LoginUser user = this.getLoginUser();
            request.setAttribute("themeIndex", pageName);
            if (user != null) {
                @SuppressWarnings("unchecked")
                List<Menu> listMenu = loginUserCtx.getUserMenus(user);
                JSONArray json = menuService.getMenuJson("0", listMenu);
                request.setAttribute("menuJson", json);
                request.setAttribute("loginUserId", user.getId());
                String zhName = user.getUserName();
                if (StringUtils.isEmpty(zhName)) {
                    zhName = user.getAccount();
                }
                request.setAttribute("loginUser", zhName);
                String orgId = user.getOrgId();
                request.setAttribute("orgId", orgId);
            } else {
                request.setAttribute("menuJson", new JSONArray());
            }
            if ("index2".equals(pageName)) {
                cfgString = "config2.js";
            } else if ("index3".equals(pageName)) {
                cfgString = "config3.js";
            }
        } else if ("error".equals(pageName)) {
            request.setAttribute("errorp", getLang("common_reqException"));//
            request.setAttribute("error", "000000000");
        }
        request.setAttribute("cfgfile", cfgString);
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        request.setAttribute("year", year);
        return super.page(pageName, request);
    }

    @Override
    public String setPageModelPath(HttpServletRequest request) {
        return "";
    }

    @RequestMapping(value = "/logout")
    public @ResponseBody AjaxResult logout(HttpServletRequest request) throws Exception {
        loginUserCtx.logout();
        return returnSuccess();
    }

    public JSONObject createImgCode(HttpServletRequest request) throws Exception {
        AjaxResult codeRes = getCode(request);
        JSONObject jOb = new JSONObject();
        jOb.put("imgKey", codeRes.message);
        jOb.put("img", codeRes.data);
        return jOb;
    }

    @RequestMapping(value = "/login")
    public @ResponseBody AjaxResult login(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String imgCode = request.getParameter("imgCode");
        String imgKey = request.getParameter("imgKey");
        Object codeObj = loginUserCtx.getKeyValue(imgKey);
        loginUserCtx.deleteKeyValue(imgKey);
        String codeValid = SysConfigParams.getConfig("imageCodeValid");
        boolean imgCodeValid = codeValid == null || codeValid.equals("true");
        String token = "";
        if (imgCodeValid && codeObj == null) {
            return returnFailData(getLang("common_imgCodeExpDate"), createImgCode(request));
        } else {
            if (!imgCodeValid || imgCode.toLowerCase().equals(String.valueOf(codeObj))) {
                String userPwd = request.getParameter("userPwd");
                String userName = request.getParameter("userName");
                // 解密
                userPwd = DESBase64Util.desDecrypt(userPwd);
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("userName", userName);
                List<User> loginUsers = userService.selectParam(params);
                if (loginUsers.size() == 0) {
                    return returnFailData(getLang("common_notExistUser"), createImgCode(request));
                } else {
                    User user = loginUsers.get(0);
                    if (user.getUserStatus().equals(0)) {
                        return returnFailData(getLang("common_userforbit"), createImgCode(request));
                    } else {
                        String pwd = DigestUtils.md5Hex(userPwd);
                        if (pwd.equals(user.getUserPwd())) {
                            LoginUser loginUser = loginUserCtx.loadUserAuthData(user);
                            String key = loginUserCtx.setLoginUser(loginUser);
                            if (StringUtils.isNotEmpty(key)) {
                                token = loginUserCtx.writeLoginCookies(loginUser);
                            } else {
                                return returnFailData(getLang("common_nosetAuthor"), createImgCode(request));
                            }
                        } else {
                            return returnFailData(getLang("common_passWdErr"), createImgCode(request));
                        }
                    }
                }
            } else {
                return returnFailData(getLang("common_imgCodeErr"), createImgCode(request));
            }
        }
        return this.returnSuccData("login ok", token);
    }

    @Override
    public boolean saveFiles(MultipartHttpServletRequest request, Map<String, MultipartFile> fileMap,
        Map<String, String> uploadResult) {
        boolean res = true;
        MultipartFile file = fileMap.get("_k_edit_upolad_file");
        String uuid = MyUUID.getUUID();
        String root = request.getServletContext().getRealPath("/");
        String origName = file.getOriginalFilename();
        String fileDir = root + "tmp";
        String fileUrl = "tmp" + File.separator + uuid + origName.substring(origName.lastIndexOf("."));
        File newfile = new File(fileDir);
        if (!newfile.exists()) {
            newfile.mkdirs();
        }
        String filePath = root + fileUrl;
        try {
            file.transferTo(new File(filePath));
            uploadResult.put("url", SysConfigParams.webHttpContext + "/" + fileUrl);
        } catch (IllegalStateException e) {
            logger.error("", e);
            res = false;
        } catch (IOException e) {
            logger.error("", e);
            res = false;
        }
        return res;
    }

    /***
     * 产生系统验证图片
     ***/
    @RequestMapping(value = "/getCode")
    public @ResponseBody AjaxResult getCode(HttpServletRequest request) throws Exception {
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        Random random = new Random();
        g.setColor(getRandColor(200, 250));
        g.fillRect(1, 1, width - 1, height - 1);
        g.setColor(getRandColor(160, 200));
        // 画随机线
        for (int i = 0; i < 20; i++) {
            int x = random.nextInt(width - 1);
            int y = random.nextInt(height - 1);
            int z = random.nextInt(5);
            if (z < 2) {
                z = 2;
            }
            g.fillRoundRect(x, y, z, z, z / 2, z / 2);
        }
        g.setColor(new Color(14, 137, 204));
        g.drawRect(0, 0, width - 1, height - 1);
        g.setFont(mFont);
        // 生成随机数,并将随机数字转换为字母
        String sRand = "";
        for (int i = 0; i < 4; i++) {
            int itmp = random.nextInt(26) + 65;
            char ctmp = (char)itmp;
            sRand += String.valueOf(ctmp);
            g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
            g.drawString(String.valueOf(ctmp), 15 * i + 8, 23);
        }
        g.dispose();
        ByteArrayOutputStream bout = new ByteArrayOutputStream(512);
        ImageIO.write(image, "PNG", bout);
        Base64 base64 = new Base64();
        String imgBase64 = "data:image/png;base64," + base64.encodeAsString(bout.toByteArray());// 返回Base64编码过的字节数组字符串

        // BASE64Encoder encoder = new BASE64Encoder();
        // String imgBase64 = "data:image/png;base64,"
        // +encoder.encode(bout.toByteArray());// 返回Base64编码过的字节数组字符串
        String imgKey = UUID.randomUUID().toString();
        loginUserCtx.setKeyValue(imgKey, sRand.toLowerCase());
        bout.close();
        return returnSuccData(imgKey, imgBase64);

    }

}
